package com.letv.whatslive.common.utils;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by wangjian7 on 2015/12/29.
 */
public class LeLiveCloudUtils {
    /**
     * 生成调用云直播参数String
     * @param params
     * @return
     */
    public static String generateParam(Map<String,String> params){
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()+"="+entry.getValue()+"&");
        }
        return sb.toString();
    }

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String o1, String o2) {
                        return o1.compareTo(o2);
                    }
                });

        sortMap.putAll(map);
        return sortMap;
    }

    /**
     * 生成签名
     * @param params
     * @param liveCloudUserSecret
     * @return
     */
    public static String generateSign(Map<String,String> params, String liveCloudUserSecret){
        StringBuffer sb = new StringBuffer();
        Map<String,String> resultMap = sortMapByKey(params);
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            sb.append(entry.getKey()+entry.getValue());
        }
        return MD5Utils.md5(sb.toString() + liveCloudUserSecret);
    }
}
